package cn.xgxd.service.Ipml;
import cn.xgxd.mapper.CartMapper;
import cn.xgxd.pojo.Goods;
import cn.xgxd.service.CartService;
import cn.xgxd.utils.RedisUtil;
import cn.xgxd.utils.UserContext;
import com.alibaba.fastjson.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.Map;

@Service
public class CartServiceIpml implements CartService {
    @Autowired
    CartMapper cartMapper;
    @Autowired
    RedisUtil redisUtil;
    @Autowired
    UserContext userContext;

    @Override
    public Boolean addCart(Goods goods) {
        String userId = userContext.getUserId();
        if (redisUtil.hget(userId,goods.getId())==null){
            Goods g = new Goods();
            g.setId(goods.getId());
            g.setImg(goods.getImg());
            g.setName(goods.getName());
            g.setPrice(goods.getPrice());
            g.setTime(new Date());
            String jsonObject =  JSONObject.toJSONString(goods);;
            redisUtil.hset(userId,goods.getId(),jsonObject);
            return true;
        }else {
            return false;
        }
    }



    @Override
    public Map selectCart() {
        String userId = userContext.getUserId();
        Map<Object, Object> hget = redisUtil.hgetall(userId);
        return hget;
    }

    @Override
    public boolean deleteCart(String id) {
        String userId = userContext.getUserId();
        if (redisUtil.hget(userId,id)==null){
            return false;
        }else {
            redisUtil.hdel(userId,id);
            return true;
        }

    }




}
